package com.zqweb.gulimall.seckill.schedule;

import com.zqweb.gulimall.seckill.service.SeckillService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SeckillSchedule {
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;
    private final String UPLOAD_LOCK = "seckill:upload:lock";

    // 定时每天的凌晨3点上架最近3天的秒杀商品
    @Scheduled(cron = "* * 22 * * ?")
//    @Async
    public void uploadLate3DaySeckillSkus(){
        // 使用分布式锁，保证分布式/高并发环境下，秒杀商品上架的幂等性
        System.out.println("上架最近3天的秒杀商品中...");
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        try {
            lock.lock(10, TimeUnit.SECONDS);
            seckillService.uploadLate3DaySeckillSkus();
        } finally {
            // 一定要确保执行完上架秒杀信息业务后，能顺利将分布式锁释放
            lock.unlock();
        }
    }

}
